//
//  DataSourceBTree.m
//  SimulacraDB
//
//  Created by Andre Cohen on 8/15/08.
//  Copyright 2008 __MyCompanyName__. All rights reserved.
//

#import "DataSourceBTree.h"
#import "PageIterator.h"
#import "BufferedPaging.h"
#import "RecordFactory.h"
#import "RecordIndexer.h"

@implementation DataSourceBTree


- (id)initWithDataSource:(NSString *)name recordPrototype:(Record *)prototype {
	[self init];
	
	recordPrototype = prototype;
	
	paging = [[[BufferedPaging alloc] initForData:name 
								   blocks:0] autorelease];
	
	
	indexes = [[[NSMutableDictionary alloc] init] autorelease];
	path = name;
	
	return self;
}

- (void)close {
	[paging close];
	NSArray *keys = [indexes allKeys];
	int i;
	for(i=0;i<[keys count];i++)
		[[indexes objectForKey:[keys objectAtIndex:i]] close];
}

- (void)insertRecord:(Record *)record {
	[paging writeRecord:record];
	NSArray *keys = [indexes allKeys];
	IndexRecord *ir = [IndexRecord createFromRecord:record];
	
	int i;
	for(i=0;i<[keys count];i++)
		[(NSObject <IndexProtocol> *)[indexes objectForKey:[keys objectAtIndex:i]] insertObject:ir];
}

- (void)removeRecord:(Record *)record {
	NSArray *keys = [indexes allKeys];
	IndexRecord *ir = [IndexRecord createFromRecord:record];
	int i;
	
	for(i=0;i<[keys count];i++)
		[(NSObject <IndexProtocol> *)[indexes objectForKey:[keys objectAtIndex:i]] removeObject:ir];
	[paging removeRecord:record];
}

- (PageIterator *)iterator {
	return [[[PageIterator alloc] initWithRecord:recordPrototype 
											page:paging] autorelease];
}

- (NSArray *)getRecord:(Record *)record usingIndex:(NSString *)index {
	return [[indexes objectForKey:index] getRecord:record];
}

- (void)addIndexWithName:(NSString *)name block:(int)block {
		[indexes setObject:[[[RecordIndexer alloc] initIndexerByBlock:block 
														 withFileName:path 
														withDataSouce:paging 
													  recordPrototype:recordPrototype] autorelease]
					forKey:name];
}

@end
